<?php 

namespace App;

use GuzzleHttp\Client;

class Ethereum
{
	protected $api_key;

	protected $client;

	public function __construct($api_key)
	{
		$this->api_key = $api_key;
		$this->client = new Client();
	}

	public function getEthBalance($address)
	{
		$url = $this->resolveUrl('getEthBalance', [$address, $this->api_key]);
		$response = $this->client->request('GET', $url);

		return $response->result;
	}

	public function getTransactionsByAddress($address, $page, $offset, $order)
	{
		$url = $this->resolveUrl('getTransactionsByAddress', [$address, $page, $offset, $order, $this->api_key]);

		$response = $this->client->request('GET', $url);

		return $response->getBody();
	}

	public function getErc20TransferEventsByAddress($contract_address, $page, $offset, $order)
	{
		$url = $this->resolveUrl('getErc20TransferEventsByAddress', [$contract_address, $page, $offset, $order, $this->api_key]);

		$response = $this->client->request('GET', $url);

		return $response->getBody();
	}

	public function resolveUrl($type, array $params)
	{
		$url_format = config('ethereum.api_urls.' . $type);
		return sprintf($url_format, ...$params);
	}

	public static function transferInputToValue($input)
	{
		$value = substr($input, -64);
		return bchexdec($value) / bcpow(10, 18);
	}


}